package com.zyh.homework.test1;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * @Author zyh
 * @Date 2024/8/13 19:19
 * @Description 使用dom4j解析XML输出到控制台
 */

public class Test2 {
    public static void main(String[] args) throws IOException, DocumentException {
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(new FileReader("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day15-code\\src\\com\\zyh\\homework\\test1\\test.xml"));
        //拿到根节点
        Element rootElement = read.getRootElement();
        System.out.println("根节点："+rootElement.getName());
        //拿到根节点下的子节点
        List<Element> elements = rootElement.elements();
        //遍历子节点
        for (Element element : elements) {
            System.out.println("\t子节点名："+element.getName()+" 子节点属性："+element.attributeValue("category"));
            //拿到所有的孙子节点
            List<Element> sunElements = element.elements();
            for (Element sunElement : sunElements) {
                System.out.println("\t\t孙子节点名："+sunElement.getName()+" 孙子节点属性："+sunElement.attributeValue("lang")+" 孙子节点的内容："+sunElement.getText());
            }
        }
    }
}
